package com.cn.qgx428.lazydiary.ui.activity

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.widget.*
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.adapter.RAdapter
import com.cn.qgx428.lazydiary.adapter.RViewHolder
import com.cn.qgx428.lazydiary.db.DatabaseHelper
import com.cn.qgx428.lazydiary.db.bean.CStikyNote
import com.cn.qgx428.lazydiary.db.dao.StikyNoteDao
import com.cn.qgx428.lazydiary.extension.getCurrentDay
import com.cn.qgx428.lazydiary.extension.switchVisible
import com.cn.qgx428.lazydiary.local.LAMessege
import com.cn.qgx428.lazydiary.local.LAction
import com.cn.qgx428.lazydiary.local.LActionWacher
import com.cn.qgx428.lazydiary.local.LManager
import com.cn.qgx428.lazydiary.ui.activity.subActivity.StickNoteChangeActivity
import kotlinx.android.synthetic.main.activity_stick_note.*
import org.jetbrains.anko.startActivity
import java.text.SimpleDateFormat
import java.util.*

class StickNoteActivity : BaseActivity(), LActionWacher {

    var defaultColor = Color.parseColor("#FFD700")
    var currentColor = Color.parseColor("#FFD700")
    var prumpTime = ""

    var colors:MutableList<Int> = mutableListOf(Color.parseColor("#339966"),Color.parseColor("#4682B4"),
            Color.parseColor("#FFD700"),Color.parseColor("#8A2BE2"),
            Color.parseColor("#119988"),Color.parseColor("#9c4b7a")
            )
    var colorAdapter = ColorAdapter(this, R.layout.adapter_stick_note_color_re, colors)

    var noteAdapter: NoteAdapter? = null
    var historyNotes: MutableList<CStikyNote>? = null

    override fun initUI() {
        hindActionBar()
        setStatuBarColor(Color.BLACK)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stick_note)

        getData()
        initView()

        LManager.newInstance().register(this, LAction.DB_DELETE_STICK_NOTE)
        LManager.newInstance().register(this, LAction.DB_UPDATE_STICK_NOTE)
    }

    fun getData(){
        var dao = StikyNoteDao()
        historyNotes = dao.getAll() as MutableList<CStikyNote>?
    }

    fun initView(){
        stikyNote_back.setOnClickListener { finish() }
        stickNote_time.text = (SimpleDateFormat("yyyy-MM-dd").format(Date()) + "  "
                + Calendar.getInstance().getCurrentDay())
        stickNote_saveBtn.setOnClickListener({
            var bean = CStikyNote()
            bean.color = currentColor
            bean.content = stickNote_input.text.toString()
            bean.createTime = stickNote_time.text.toString()
            bean.noticeTime = prumpTime
           // var dao = DatabaseHelper.newInstance().newDao(StikyNoteDao::class.java) as StikyNoteDao
            var dao = StikyNoteDao()
            dao.add(bean)
            //刷新当前列表，清理输入页面
            historyNotes?.add(0,bean)
            noteAdapter?.setDatas(historyNotes!!)
            stickNote_input.setText("")
            prumpTime = ""
            stickNote_prumpLayout.visibility = View.GONE
            //通知
            LManager.newInstance().trigger(LAction.DB_UPDATE_STICK_NOTE)
        })

        /**
         * 颜色列表
         */
        stickNote_colorRe.adapter = colorAdapter;
        var layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        stickNote_colorRe.layoutManager = layoutManager
        colorAdapter.setColorListener(object: ColorAdapter.ColorListener{
            override fun onGetColorValue(color: Int) {
                stickNote_inputLayout.setBackgroundColor(color)
                currentColor = color
            }
        })

        stickNote_colorBtn.setOnClickListener({
            stickNote_colorRe.switchVisible()
        })

        //闹钟
        stickNote_clock.setOnClickListener({
            setNotice()
        })

        /**
         * 历史便签列表
         */
        noteAdapter = NoteAdapter(this, R.layout.adapter_stick_note_history_re, historyNotes!!)
        stickNote_historyRe.adapter = noteAdapter
        stickNote_historyRe.layoutManager = LinearLayoutManager(this)
    }

    private fun setNotice() {
        // 具体时间选择
        val mDialog = getTimePickerDialog(object : TimePickerDialog.OnTimeSetListener{
            override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                prumpTime = prumpTime + "${hourOfDay.toString()}时${minute.toString()}分"
                val index = prumpTime.indexOf("年")
                stickNote_prumpTime.text = prumpTime.substring(index+1)
                stickNote_prumpLayout.visibility = View.VISIBLE
            }
        })
        mDialog.setOnCancelListener({
            mDialog.dismiss()
            prumpTime = ""
            stickNote_prumpLayout.visibility = View.GONE
        })

        // 日期选择
         val dDialog = getDatePickerDialog(object : DatePickerDialog.OnDateSetListener{
            override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                val builder = StringBuilder()
                builder.append(year.toString() + "年")
                val cMouth = month + 1
                if (cMouth.toString().length == 1){
                    builder.append("0" + cMouth.toString() + "月")
                } else{
                    builder.append(cMouth.toString() + "月")
                }
                if (dayOfMonth.toString().length == 1){
                    builder.append("0" + dayOfMonth.toString() + "日")
                } else{
                    builder.append(dayOfMonth.toString() + "日")
                }
                prumpTime = builder.toString()
                mDialog.show()
            }
        })
        val start = System.currentTimeMillis()
        dDialog.datePicker.minDate = start
        dDialog.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        LManager.newInstance().unRegister(this)
    }

    override fun onTrigger(action: String, msg: LAMessege) {
        if (action.equals(LAction.DB_DELETE_STICK_NOTE)){
            getData()
            noteAdapter?.setDatas(historyNotes!!)
        }
        if (action.equals(LAction.DB_UPDATE_STICK_NOTE)){
            getData()
            noteAdapter?.setDatas(historyNotes!!)
        }
    }

    /*********分界线**********/
    class ColorAdapter (context: Context, layoutId: Int, colors: MutableList<Int>): RAdapter<Int>(context, layoutId, colors){

        interface ColorListener{
            fun onGetColorValue(color: Int)
        }

        var mColorListener: ColorListener? = null

        override fun conver(holder: RViewHolder, data: Int) {
            var imgView: ImageView = holder.getView(R.id.activity_stickNote_colorRe_img)!!
            imgView.setTag(data)
            imgView.setBackgroundColor(data)
            imgView.setOnClickListener {
                mColorListener?.onGetColorValue(imgView.getTag() as Int)
            }
        }

        public fun setColorListener(colorListener: ColorListener){
            mColorListener = colorListener
        }
    }

    /*********分界线**********/
    class NoteAdapter(context: Context, layoutId: Int, notes: MutableList<CStikyNote>): RAdapter<CStikyNote>(context,layoutId,notes){
        override fun conver(holder: RViewHolder, data: CStikyNote) {
            var text: TextView = holder.getView(R.id.stickNote_historyRe_input)!!
            var time : TextView = holder.getView(R.id.stickNote_historyRe_time)!!
            var bg : LinearLayout = holder.getView(R.id.stickNote_historyRe_layout)!!
            var promptTxt: TextView = holder.getView(R.id.stickNote_historyRe_promptTxt)!!
            var proptLayout: LinearLayout = holder.getView(R.id.stickNote_historyRe_promptLayout)!!

            text.setText(data.content)
            time.setText(data.createTime)
            if (TextUtils.isEmpty(data.noticeTime)){
                proptLayout.visibility = View.GONE
            }else{
                proptLayout.visibility = View.VISIBLE
                var timeString = data.noticeTime
                val startIndex = timeString!!.indexOf("年")
                promptTxt.text = timeString.substring(startIndex+1)
            }
            bg.setBackgroundColor(data.color)
            bg.setOnClickListener({
                var intent = Intent(mContext, StickNoteChangeActivity::class.java)
                var bundle = Bundle()
                bundle.putSerializable(MConst.S_STICK_NOTE,data)
                intent.putExtras(bundle)
                mContext.startActivity(intent)
            })
        }
    }
}
